/*
 * @Description:
 * @Version: 2.0
 * @Autor: Seven
 * @Date: 2025-04-01 10:33:04
 * @LastEditors: Seven
 * @LastEditTime: 2025-06-10 15:40:28
 */
// 创建扇环几何体
export function createAnnularSector(centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
  // 复用网格线的精确计算函数
  const computePoint = (center, radius, angle) => {
    const ellipsoid = Cesium.Ellipsoid.WGS84;
    const centerCartesian = Cesium.Cartesian3.fromDegrees(...center);
    const tangentPlane = new Cesium.EllipsoidTangentPlane(centerCartesian, ellipsoid);

    const eastOffset = radius * Math.sin(Cesium.Math.toRadians(angle));
    const northOffset = radius * Math.cos(Cesium.Math.toRadians(angle));

    const offsetCartesian = tangentPlane.projectPointOntoEllipsoid(
      new Cesium.Cartesian2(eastOffset, northOffset)
    );

    return offsetCartesian;
  };

  const positions = [];
  const ARC_SEGMENTS = 100; // 与网格线相同的分段数

  // 1. 外圆弧（从起始角到终止角）
  for (let i = 0; i <= ARC_SEGMENTS; i++) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    positions.push(computePoint(centerLonLat, outerRadius, angle));
  }

  // 2. 内圆弧（从终止角到起始角，反向连接）
  for (let i = ARC_SEGMENTS; i >= 0; i--) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    positions.push(computePoint(centerLonLat, innerRadius, angle));
  }

  // 闭合多边形（连接回起点）
  positions.push(positions[0].clone());

  return positions;
}
export function addSectorGrid(viewer, centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
  // ======== 参数说明 ========
  // viewer: Cesium Viewer实例
  // centerLonLat: 中心点坐标 [经度, 纬度]（单位：度）
  // innerRadius: 内半径（单位：米）
  // outerRadius: 外半径（单位：米）
  // startAngle: 起始角度（单位：度，0=正北，顺时针增加）
  // endAngle: 结束角度（单位：度）

  // ======== 常量配置 ========
  const RADIAL_SPACING = 6.4;        // 径向线角度间隔（度）
  const ANGLE_LABEL_SPACING = 200000; // 角度标签间距（米）
  const ARC_SPACING = 100000;         // 圆弧半径间隔（米）
  const DISTANCE_LABEL_SPACING = 200000; // 距离标签间距（米）
  const ARC_SEGMENTS = 100;            // 每段圆弧的分段数
  const LABEL_HEIGHT = 10000;         // 标签高度（米）

  // ======== 辅助函数：计算目标点坐标 ========
  const computePoint = (center, radius, angle) => {
    const ellipsoid = Cesium.Ellipsoid.WGS84;
    const centerCartesian = Cesium.Cartesian3.fromDegrees(...center);
    const tangentPlane = new Cesium.EllipsoidTangentPlane(centerCartesian, ellipsoid);

    // 计算局部坐标偏移（东方向，北方向）
    const eastOffset = radius * Math.sin(Cesium.Math.toRadians(angle));
    const northOffset = radius * Math.cos(Cesium.Math.toRadians(angle));

    // 将局部坐标转换为椭球面坐标
    const offsetCartesian = tangentPlane.projectPointOntoEllipsoid(
      new Cesium.Cartesian2(eastOffset, northOffset)
    );

    // 转换为经纬度
    const cartographic = ellipsoid.cartesianToCartographic(offsetCartesian);
    return {
      cartographic,
      cartesian: offsetCartesian
    };
  };

  // ======== 标签样式配置 ========
  // 统一标签样式 - 非粗体字体
  const labelStyle = {
    font: '14px sans-serif', // 非粗体字体
    fillColor: Cesium.Color.CYAN,
    outlineColor: Cesium.Color.WHITE,
    outlineWidth: 2,
    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
    verticalOrigin: Cesium.VerticalOrigin.CENTER,
    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
    heightReference: Cesium.HeightReference.NONE,
    disableDepthTestDistance: Number.POSITIVE_INFINITY,
    scale: 0.9, // 轻微缩放提高清晰度
    pixelOffsetScaleByDistance: new Cesium.NearFarScalar(1.0e3, 1.0, 2.0e6, 0.1), // 随距离调整大小
    translucencyByDistance: new Cesium.NearFarScalar(1.0e3, 1.0, 2.0e6, 0.5) // 随距离调整透明度
  };

  const angleLabelStyle = {
    ...labelStyle,
    font: '16px sans-serif' // 角度标签稍大但同样非粗体
  };

  // ======== 1. 生成径向线（从内到外） ========
  const radialCount = Math.ceil((endAngle - startAngle) / RADIAL_SPACING) + 1;

  for (let i = 0; i < radialCount; i++) {
    const angle = Math.min(startAngle + i * RADIAL_SPACING, endAngle);

    // 计算径向线起点和终点
    const startPoint = computePoint(centerLonLat, innerRadius, angle);
    const endPoint = computePoint(centerLonLat, outerRadius, angle);

    // 直接添加径向线实体
    viewer.entities.add({
      polyline: {
        positions: [
          Cesium.Cartesian3.fromRadians(
            startPoint.cartographic.longitude,
            startPoint.cartographic.latitude
          ),
          Cesium.Cartesian3.fromRadians(
            endPoint.cartographic.longitude,
            endPoint.cartographic.latitude
          )
        ],
        width: 1,
        material: Cesium.Color.WHITE,
        clampToGround: true
      }
    });

    // 在径向线末端添加角度标签（每隔200km）
    if (Math.abs(angle - startAngle) > 0.1 && Math.abs(angle - endAngle) > 0.1) {
      const labelRadius = Math.ceil(outerRadius / ANGLE_LABEL_SPACING) * ANGLE_LABEL_SPACING;
      if (labelRadius <= outerRadius) {
        const labelPoint = computePoint(centerLonLat, outerRadius, angle);

        // 计算标签位置偏移量（沿径向线方向向外延伸5%）
        const direction = Cesium.Cartesian3.subtract(
          labelPoint.cartesian,
          Cesium.Cartesian3.fromDegrees(...centerLonLat),
          new Cesium.Cartesian3()
        );
        Cesium.Cartesian3.normalize(direction, direction);

        // 添加高度偏移，确保标签可见
        const labelPosition = Cesium.Cartesian3.add(
          labelPoint.cartesian,
          Cesium.Cartesian3.multiplyByScalar(
            Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(labelPoint.cartesian),
            LABEL_HEIGHT,
            new Cesium.Cartesian3()
          ),
          new Cesium.Cartesian3()
        );

        // 沿径向线方向再向外偏移
        const finalPosition = Cesium.Cartesian3.add(
          labelPosition,
          Cesium.Cartesian3.multiplyByScalar(direction, outerRadius * 0.05, new Cesium.Cartesian3()),
          new Cesium.Cartesian3()
        );

        viewer.entities.add({
          position: finalPosition,
          label: {
            text: `${angle.toFixed(1)}°`,
            ...labelStyle // 使用统一的标签样式
          }
        });
      }
    }
  }

  // ======== 2. 生成同心圆弧和距离标签 ========
  const arcCount = Math.ceil((outerRadius - innerRadius) / ARC_SPACING) + 1;

  for (let i = 0; i < arcCount; i++) {
    const currentRadius = Math.min(innerRadius + i * ARC_SPACING, outerRadius);

    // 直接创建圆弧点数组
    const arcPositions = [];
    for (let j = 0; j <= ARC_SEGMENTS; j++) {
      const angle = startAngle + (endAngle - startAngle) * (j / ARC_SEGMENTS);
      const point = computePoint(centerLonLat, currentRadius, angle);
      arcPositions.push(
        Cesium.Cartesian3.fromRadians(
          point.cartographic.longitude,
          point.cartographic.latitude
        )
      );
    }

    // 添加圆弧实体
    viewer.entities.add({
      polyline: {
        positions: arcPositions,
        width: 1,
        material: Cesium.Color.WHITE,
        clampToGround: true
      }
    });
  }

  // ======== 3. 添加距离标签（每隔200公里） ========
  const distanceLabelCount = Math.ceil((outerRadius - innerRadius) / DISTANCE_LABEL_SPACING) + 1;

  for (let i = 0; i < distanceLabelCount; i++) {
    const currentRadius = Math.min(innerRadius + i * DISTANCE_LABEL_SPACING, outerRadius);

    // 在开始角度位置添加距离标签
    const startLabelPoint = computePoint(centerLonLat, currentRadius, startAngle);
    // 在结束角度位置添加距离标签
    const endLabelPoint = computePoint(centerLonLat, currentRadius, endAngle);

    // 计算标签位置偏移量（沿径向线方向向外延伸5%）
    const startDirection = Cesium.Cartesian3.subtract(
      startLabelPoint.cartesian,
      Cesium.Cartesian3.fromDegrees(...centerLonLat),
      new Cesium.Cartesian3()
    );
    Cesium.Cartesian3.normalize(startDirection, startDirection);

    const endDirection = Cesium.Cartesian3.subtract(
      endLabelPoint.cartesian,
      Cesium.Cartesian3.fromDegrees(...centerLonLat),
      new Cesium.Cartesian3()
    );
    Cesium.Cartesian3.normalize(endDirection, endDirection);

    // 添加高度偏移，确保标签可见
    const startLabelPosition = Cesium.Cartesian3.add(
      startLabelPoint.cartesian,
      Cesium.Cartesian3.multiplyByScalar(
        Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(startLabelPoint.cartesian),
        LABEL_HEIGHT,
        new Cesium.Cartesian3()
      ),
      new Cesium.Cartesian3()
    );

    const endLabelPosition = Cesium.Cartesian3.add(
      endLabelPoint.cartesian,
      Cesium.Cartesian3.multiplyByScalar(
        Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(endLabelPoint.cartesian),
        LABEL_HEIGHT,
        new Cesium.Cartesian3()
      ),
      new Cesium.Cartesian3()
    );

    // 沿径向线方向再向外偏移
    const finalStartPosition = Cesium.Cartesian3.add(
      startLabelPosition,
      Cesium.Cartesian3.multiplyByScalar(startDirection, currentRadius * 0.05, new Cesium.Cartesian3()),
      new Cesium.Cartesian3()
    );

    const finalEndPosition = Cesium.Cartesian3.add(
      endLabelPosition,
      Cesium.Cartesian3.multiplyByScalar(endDirection, currentRadius * 0.05, new Cesium.Cartesian3()),
      new Cesium.Cartesian3()
    );

    // 添加开始角度位置的距离标签
    viewer.entities.add({
      position: finalStartPosition,
      label: {
        text: `${(currentRadius / 1000).toFixed(0)} km`,
        ...labelStyle // 使用统一的标签样式
      }
    });

    // 添加结束角度位置的距离标签
    viewer.entities.add({
      position: finalEndPosition,
      label: {
        text: `${(currentRadius / 1000).toFixed(0)} km`,
        ...labelStyle // 使用统一的标签样式
      }
    });
  }

  // ======== 4. 添加起始和结束角度标签 ========
  const startLabelPoint = computePoint(centerLonLat, outerRadius, startAngle);
  const endLabelPoint = computePoint(centerLonLat, outerRadius, endAngle);

  // 计算标签位置偏移量（沿径向线方向向外延伸10%）
  const startDirection = Cesium.Cartesian3.subtract(
    startLabelPoint.cartesian,
    Cesium.Cartesian3.fromDegrees(...centerLonLat),
    new Cesium.Cartesian3()
  );
  Cesium.Cartesian3.normalize(startDirection, startDirection);

  const endDirection = Cesium.Cartesian3.subtract(
    endLabelPoint.cartesian,
    Cesium.Cartesian3.fromDegrees(...centerLonLat),
    new Cesium.Cartesian3()
  );
  Cesium.Cartesian3.normalize(endDirection, endDirection);

  // 添加高度偏移
  const startLabelPosition = Cesium.Cartesian3.add(
    startLabelPoint.cartesian,
    Cesium.Cartesian3.multiplyByScalar(
      Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(startLabelPoint.cartesian),
      LABEL_HEIGHT * 1.2,
      new Cesium.Cartesian3()
    ),
    new Cesium.Cartesian3()
  );

  const endLabelPosition = Cesium.Cartesian3.add(
    endLabelPoint.cartesian,
    Cesium.Cartesian3.multiplyByScalar(
      Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(endLabelPoint.cartesian),
      LABEL_HEIGHT * 1.2,
      new Cesium.Cartesian3()
    ),
    new Cesium.Cartesian3()
  );

  // 沿径向线方向再向外偏移
  const finalStartPosition = Cesium.Cartesian3.add(
    startLabelPosition,
    Cesium.Cartesian3.multiplyByScalar(startDirection, outerRadius * 0.1, new Cesium.Cartesian3()),
    new Cesium.Cartesian3()
  );

  const finalEndPosition = Cesium.Cartesian3.add(
    endLabelPosition,
    Cesium.Cartesian3.multiplyByScalar(endDirection, outerRadius * 0.1, new Cesium.Cartesian3()),
    new Cesium.Cartesian3()
  );

  viewer.entities.add({
    position: finalStartPosition,
    label: {
      text: `${startAngle.toFixed(1)}°`,
      ...angleLabelStyle, // 使用角度标签样式
      fillColor: Cesium.Color.YELLOW,
      outlineWidth: 3
    }
  });

  viewer.entities.add({
    position: finalEndPosition,
    label: {
      text: `${endAngle.toFixed(1)}°`,
      ...angleLabelStyle, // 使用角度标签样式
      fillColor: Cesium.Color.YELLOW,
      outlineWidth: 3
    }
  });

  // ======== 5. 闭合边界线 ========
  // 内圆弧
  const innerArcPositions = [];
  for (let i = 0; i <= ARC_SEGMENTS; i++) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    const point = computePoint(centerLonLat, innerRadius, angle);
    innerArcPositions.push(
      Cesium.Cartesian3.fromRadians(
        point.cartographic.longitude,
        point.cartographic.latitude
      )
    );
  }
  viewer.entities.add({
    polyline: {
      positions: innerArcPositions,
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });

  // 外圆弧
  const outerArcPositions = [];
  for (let i = 0; i <= ARC_SEGMENTS; i++) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    const point = computePoint(centerLonLat, outerRadius, angle);
    outerArcPositions.push(
      Cesium.Cartesian3.fromRadians(
        point.cartographic.longitude,
        point.cartographic.latitude
      )
    );
  }
  viewer.entities.add({
    polyline: {
      positions: outerArcPositions,
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });

  // 起始角度边界线
  viewer.entities.add({
    polyline: {
      positions: [
        innerArcPositions[0],
        outerArcPositions[0]
      ],
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });

  // 结束角度边界线
  const lastInnerIndex = innerArcPositions.length - 1;
  const lastOuterIndex = outerArcPositions.length - 1;
  viewer.entities.add({
    polyline: {
      positions: [
        innerArcPositions[lastInnerIndex],
        outerArcPositions[lastOuterIndex]
      ],
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
}

export function addSectorGridSmall(viewer, centerLonLat, innerRadius, outerRadius, startAngle, endAngle) {
  const entities = []; // 存储本次创建的所有实体
  // ======== 常量配置 ========
  const RADIAL_SPACING = 6.4;        // 径向线角度间隔（度）
  const ARC_SPACING = 100000;         // 圆弧半径间隔（米）
  const ARC_SEGMENTS = 100;            // 每段圆弧的分段数

  // ======== 辅助函数：计算目标点坐标 ========
  const computePoint = (center, radius, angle) => {
    const ellipsoid = Cesium.Ellipsoid.WGS84;
    const centerCartesian = Cesium.Cartesian3.fromDegrees(...center);
    const tangentPlane = new Cesium.EllipsoidTangentPlane(centerCartesian, ellipsoid);

    // 计算局部坐标偏移（东方向，北方向）
    const eastOffset = radius * Math.sin(Cesium.Math.toRadians(angle));
    const northOffset = radius * Math.cos(Cesium.Math.toRadians(angle));

    // 将局部坐标转换为椭球面坐标
    const offsetCartesian = tangentPlane.projectPointOntoEllipsoid(
      new Cesium.Cartesian2(eastOffset, northOffset)
    );

    // 转换为经纬度
    const cartographic = ellipsoid.cartesianToCartographic(offsetCartesian);
    return {
      cartographic,
      cartesian: offsetCartesian
    };
  };

  // ======== 1. 生成径向线（从内到外） ========
  const radialCount = Math.ceil((endAngle - startAngle) / RADIAL_SPACING) + 1;

  for (let i = 0; i < radialCount; i++) {
    const angle = Math.min(startAngle + i * RADIAL_SPACING, endAngle);

    // 计算径向线起点和终点
    const startPoint = computePoint(centerLonLat, innerRadius, angle);
    const endPoint = computePoint(centerLonLat, outerRadius, angle);

    // 直接添加径向线实体
    const entity = viewer.entities.add({
      polyline: {
        positions: [
          Cesium.Cartesian3.fromRadians(
            startPoint.cartographic.longitude,
            startPoint.cartographic.latitude
          ),
          Cesium.Cartesian3.fromRadians(
            endPoint.cartographic.longitude,
            endPoint.cartographic.latitude
          )
        ],
        width: 1,
        material: Cesium.Color.WHITE,
        clampToGround: true
      }
    });
    entities.push(entity);
  }

  // ======== 2. 生成同心圆弧 ========
  const arcCount = Math.ceil((outerRadius - innerRadius) / ARC_SPACING) + 1;

  for (let i = 0; i < arcCount; i++) {
    const currentRadius = Math.min(innerRadius + i * ARC_SPACING, outerRadius);

    // 创建圆弧点数组
    const arcPositions = [];
    for (let j = 0; j <= ARC_SEGMENTS; j++) {
      const angle = startAngle + (endAngle - startAngle) * (j / ARC_SEGMENTS);
      const point = computePoint(centerLonLat, currentRadius, angle);
      arcPositions.push(
        Cesium.Cartesian3.fromRadians(
          point.cartographic.longitude,
          point.cartographic.latitude
        )
      );
    }

    // 添加圆弧实体
    const entity = viewer.entities.add({
      polyline: {
        positions: arcPositions,
        width: 1,
        material: Cesium.Color.WHITE,
        clampToGround: true
      }
    });
    entities.push(entity);
  }

  // ======== 3. 生成扇环边界线 ========
  // 内圆弧
  const innerArcPositions = [];
  for (let i = 0; i <= ARC_SEGMENTS; i++) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    const point = computePoint(centerLonLat, innerRadius, angle);
    innerArcPositions.push(
      Cesium.Cartesian3.fromRadians(
        point.cartographic.longitude,
        point.cartographic.latitude
      )
    );
  }
  const innerArcEntity = viewer.entities.add({
    polyline: {
      positions: innerArcPositions,
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
  entities.push(innerArcEntity);

  // 外圆弧
  const outerArcPositions = [];
  for (let i = 0; i <= ARC_SEGMENTS; i++) {
    const angle = startAngle + (endAngle - startAngle) * (i / ARC_SEGMENTS);
    const point = computePoint(centerLonLat, outerRadius, angle);
    outerArcPositions.push(
      Cesium.Cartesian3.fromRadians(
        point.cartographic.longitude,
        point.cartographic.latitude
      )
    );
  }
  const outerArcEntity = viewer.entities.add({
    polyline: {
      positions: outerArcPositions,
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
  entities.push(outerArcEntity);

  // 起始角度边界线
  const startBoundaryEntity = viewer.entities.add({
    polyline: {
      positions: [
        innerArcPositions[0],
        outerArcPositions[0]
      ],
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
  entities.push(startBoundaryEntity);
  // 结束角度边界线
  const lastInnerIndex = innerArcPositions.length - 1;
  const lastOuterIndex = outerArcPositions.length - 1;
  const endBoundaryEntity = viewer.entities.add({
    polyline: {
      positions: [
        innerArcPositions[lastInnerIndex],
        outerArcPositions[lastOuterIndex]
      ],
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
  entities.push(endBoundaryEntity);
  return entities; // 返回所有创建的实体
}


